package com.crawler.harbour.utils;

import com.alibaba.fastjson.JSONObject;
import com.crawler.harbour.dto.DaZhaKouOutDto;
import com.crawler.harbour.dto.LoginParamsDto;
import com.google.common.collect.Maps;

import net.dongliu.requests.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 登入
 * @author wbsheng
 * @create 2018-03-30 14:11
 **/
public class LoginUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoginUtil.class);
    
    private static final Map<String,Session> sessionCache = Maps.newConcurrentMap();
    

    /**
     *厦门海通码头 登入
     * @param session
     * @return
     */
    public static String getJsTicket(Session session, LoginParamsDto params){
        //获取sessionId
        Response<String> defaultRespon = session.get(params.getSessionUrl()).send().toTextResponse();
        String sessionId=defaultRespon.getCookie(params.getSessionName()).getValue();
        LOGGER.info("get SessionId: "+sessionId);
        Map<String,String>param=new HashMap<>();
        param.put("username","Z3Vlc3Q=");
        param.put("password","MTIz");
        param.put("Action","Login");
        Response<String> validateRespon = session.post(params.getLoginUrl()).forms(param).send().toTextResponse();
        String jsTicket=validateRespon.getCookie(params.getJsTicketName()).getValue();
        LOGGER.info("get JsTicket: "+jsTicket);
        return  jsTicket;
    }
    
    
    /**
     *厦门集装箱码头集团 登入
     * @param session
     * @return
     */
    public static String getXHCTJsTicket(Session session, LoginParamsDto params){
        //获取sessionId
        Response<String> defaultRespon = session.get(params.getSessionUrl()).send().toTextResponse();
        String sessionId=defaultRespon.getCookie(params.getSessionName()).getValue();
        LOGGER.info("get SessionId: "+sessionId);
        Map<String,String>param=new HashMap<>();
        param.put("username",AESUtil.xhct("guest", sessionId));
        param.put("password",AESUtil.xhct("123", sessionId));
        param.put("Action","Login");
        Response<String> validateRespon = session.post(params.getLoginUrl()).forms(param).send().toTextResponse();
        String jsTicket=validateRespon.getCookie(params.getJsTicketName()).getValue();
        LOGGER.info("get JsTicket: "+jsTicket);
        return  jsTicket;
    }
    
    public static Session daZhaKouPreLogin(String userName,String password) {
    	Session session = sessionCache.get(userName);
    	if(session==null) {
    		session = Requests.session();
    		sessionCache.put(userName, session);
    	}
    	//拖车入港
        Response<String> stringResponse = session.get("https://www.china-xmftz.gov.cn/views/app/goto.aspx?id=24").send().toTextResponse();
        Document document = Jsoup.parse(stringResponse.getBody());
        Element form = document.getElementById("form2");
        if(form==null) {
        	 int retryTime = 5;
             while(retryTime>0) {
        		 try {
        			 daZhaKouLogin(session, userName, password);
        			 break;
                 }catch (Exception e) {
                 	retryTime--;
                }
     	   	}
        }
        return session;
    }
    
    /**
     * 大闸口报备登入
     * @param session
     */
    private static void daZhaKouLogin(Session session,String userName,String password) {
        session.get(UrlUtil.DAZHAKOULOGIN).verify(false).send();
        Random r=new Random();
        //首页
        session.get("https://www.china-xmftz.gov.cn").send();
        //刷新验证码
        RawResponse send = session.get("https://www.china-xmftz.gov.cn/Captcha.aspx?0.0776692707696431"+r.nextInt(10)).verify(false).send();
        //解析验证码
        String codeResult = RuoKuai.createByPost(send.readToBytes());
        JSONObject codeJson = JSONObject.parseObject(codeResult);
        System.out.println(codeResult);
        String captcha=codeJson.get("Result").toString();
        //登入
        Map<String,String > queryParams=new HashMap<>();
        queryParams.put("UserName",userName);
        queryParams.put("Password",password);
        queryParams.put("captcha",captcha);
        session.post("https://www.china-xmftz.gov.cn/Controllers/CommonAction.ashx?__method=login").verify(false).forms(queryParams).send().toTextResponse();

        //拖车入港
        Response<String> stringResponse = session.get("https://www.china-xmftz.gov.cn/views/app/goto.aspx?id=24").send().toTextResponse();
        Document document = Jsoup.parse(stringResponse.getBody());
        Map<String,String>param=new HashMap<>();
        Element form = document.getElementById("form2");
        Elements input = form.getElementsByTag("input");
        for (Element e:input) {
            param.put(e.attr("name"),e.val());
        }
        //获取cookie
        session.post("https://tqbb.china-xmftz.gov.cn:8099/TrailerNumberInfoAdd.aspx").forms(param).send().toTextResponse();

    }
}
